//
//  HXSearchBtnVC.m
//  ZCooking
//
//  Created by 韩旭 on 16/8/29.
//  Copyright © 2016年 HX_. All rights reserved.
//

#import "HXSearchBtnVC.h"
#import "HX_Macro.h"
#import "HXSearchBarCCell.h"
#import "HXHostoryCCell.h"
#import "ZYPinYinSearch.h"
#import "HXSearchModel.h"
#import "ChineseString.h"
#import "ZYTokenManager.h"
#import "HXSearchDetailCell.h"
#import "HXSearchDetailVC.h"
@interface HXSearchBtnVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, assign) BOOL isSearch;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *keyText;
@property (nonatomic, strong) NSMutableArray *search;
@property (nonatomic, strong) NSMutableArray *allDataSource;
@property (nonatomic, strong) NSMutableArray *indexArray;
@property (nonatomic, strong) NSArray *history;
@end

@implementation HXSearchBtnVC
- (NSArray *)history {
    if (!_history) {
        self.history = [NSMutableArray array];
    }
    return _history;
}
- (NSMutableArray *)indexArray {
    if (!_indexArray) {
        _indexArray = [NSMutableArray array];
    }
    return _indexArray;
}
- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}
- (NSMutableArray *)search {
    if (!_search) {
        _search = [NSMutableArray array];
    }
    return _search;
}
- (NSMutableArray *)allDataSource {
    if (!_allDataSource) {
        _allDataSource = [NSMutableArray array];
    }
    return _allDataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.isSearch = NO;
    //    [ZYTokenManager removeAllArray];
    self.history = nil;
    self.view.backgroundColor = [UIColor darkGrayColor];
    self.title = @"搜索vc";
    [self readWithNSUserDefult];
    self.navigationItem.titleView = self.searchBar;
    [self.view addSubview:self.collectionView];
    if (self.isSearch == YES) {
        [self tableView];
    }
    [self initData];
}
- (void)getNetSearchBtnWoking:(NSString *)searchText {
    NSString *url = @"http://api.izhangchu.com";
    NSString *bodyString = [NSString stringWithFormat:@"methodName=SearchKeyword&keyword=%@&version=4.40&", searchText];
    NSDictionary *dicHeader = @{@"Content-Type" : @"application/x-www-form-urlencoded; charset=utf-8"};
    [HXNetTool postNetWithUrl:url body:bodyString BodyStyle:HXBodyString Header:dicHeader Response:HXJSON Success:^(id result) {
        NSDictionary *results = result;
        NSDictionary *dicData = results[@"data"];
        NSArray *arrData = dicData[@"data"];
        for (NSDictionary *dicAll in arrData) {
            HXSearchModel *searchModel = [HXSearchModel ModelWithDic:dicAll];
            [self.search addObject:searchModel.text];
        }
        self.indexArray = [ChineseString IndexArray:self.search];
        self.allDataSource = [ChineseString LetterSortArray:self.search];
        [_tableView reloadData];
    } Failure:^(NSError *error) {
    }];
}
- (void)initData {
    _dataSource = @[@"土豆", @"鱿鱼", @"黄瓜", @"南瓜", @"炒"];
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:0];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableView"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 44)];
        _searchBar.backgroundColor = [UIColor whiteColor];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索";
        _searchBar.showsCancelButton = NO;
    }
    return _searchBar;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 0);
        layout.headerReferenceSize = CGSizeMake(0, 44);
        layout.scrollDirection = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"HXSearchBarCCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"HXSearchBarCCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"searHeader"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionHeader"];
        [_collectionView registerNib:[UINib nibWithNibName:@"HXHostoryCCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"HXHostoryCCell"];
    }
    return _collectionView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.indexArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.allDataSource[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableView"];
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.text = self.allDataSource[indexPath.section][indexPath.row];
    return cell;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        if (_history > 0) {
            return _history.count;
        } else {
            return 0;
        }
    } else {
        return _dataSource.count;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HXHostoryCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HXHostoryCCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        NSArray *arrAll = [[self.history reverseObjectEnumerator] allObjects];
        cell.cellLabel.text = arrAll[indexPath.row];
        return cell;
    } else {
        HXSearchBarCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HXSearchBarCCell" forIndexPath:indexPath];
        cell.searLabel.text = self.dataSource[indexPath.row];
        cell.searLabel.layer.borderWidth = 2;
        cell.searLabel.layer.borderColor = [UIColor orangeColor].CGColor;
        cell.backgroundColor = [UIColor whiteColor];
        cell.layer.cornerRadius = 5;
        return cell;
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        CGFloat width = [SelfSizeTools selfSizeHeightWithString:self.dataSource[indexPath.row] height:20 Font:[UIFont systemFontOfSize:17]];
        return CGSizeMake(width, 20);
    } else {
        return CGSizeMake((self.collectionView.HX_width - 20) / 2, 20);
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UICollectionReusableView *headerViews = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"searHeader" forIndexPath:indexPath];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"清空历史搜索" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:17];
        btn.HX_x = 10;
        btn.HX_y = 0;
        btn.HX_width = [SelfSizeTools selfSizeHeightWithString:@"清空历史搜索" height:44 Font:[UIFont systemFontOfSize:17]];
        [btn addTarget:self action:@selector(cleanBtn:) forControlEvents:UIControlEventTouchUpInside];
        btn.HX_height = 44;
        [headerViews addSubview:btn];
        return headerViews;
    } else {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionHeader" forIndexPath:indexPath];
        UILabel *lable = [[UILabel alloc] init];
        lable.text = @"热门搜索";
        lable.HX_x = 10;
        lable.HX_y = 0;
        lable.HX_width = SCREEN_WIDTH;
        lable.HX_height = 44;
        [headerView addSubview:lable];
        return headerView;
    }
}
- (void)cleanBtn:(UIButton *)btn {
    if (self.history.count == 0) {
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有可清理的记录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actOne = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
            [ZYTokenManager removeAllArray];
            self.history = nil;
            [_collectionView reloadData];
        }];
        
        [alertControl addAction:actOne];
        [self presentViewController:alertControl animated:YES completion:nil];
    } else {
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"警告" message:@"是否清除历史记录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actOne = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [ZYTokenManager removeAllArray];
        self.history = nil;
         [_collectionView reloadData];
    }];
    
    [alertControl addAction:actOne];
    [self presentViewController:alertControl animated:YES completion:nil];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HXSearchDetailVC *detail = [[HXSearchDetailVC alloc] init];
    NSString *string = self.allDataSource[indexPath.section][indexPath.row];
    [ZYTokenManager SearchText:string];
    [self readWithNSUserDefult];
    self.tableView.hidden = YES;
    detail.netString = string;
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)readWithNSUserDefult{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSArray *AR  = [user arrayForKey:@"myArray"];
    self.history = AR;
    [_collectionView reloadData];
}
#pragma mark  UISearchBarDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length == 0) {
        _isSearch = NO;
        self.tableView.hidden = YES;
    }else{
        self.tableView.hidden = NO;
        [self getNetSearchBtnWoking:searchText];
        _isSearch = YES;
    }
    [_tableView reloadData];
    
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [UIView animateWithDuration:0.3 animations:^{
        _searchBar.showsCancelButton = YES;
    }];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _searchBar.frame = CGRectMake(0, 64, WIDETH, 44);
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    _isSearch = YES;
    [_tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
